import React, {useRef, useState} from 'react';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {OrderTrade} from './data.d';
import {queryType} from "./data.d";
import {orderTrade, queryFutuersList, querySymbols} from './service';
import {queryUse, queryUseUpdate} from "@/utils/service";
import {columnsSorter, columnToColumnsState, empty, formatDate, formatNumPercent} from "@/utils/function";
import {Button, Divider, message, Modal, Popconfirm} from "antd";
import {PlusOutlined} from "@ant-design/icons/lib";
import {PageContainer} from "@ant-design/pro-layout";
import {ModalForm, ProFormDigit, ProFormSelect} from "@ant-design/pro-form";
import FutuersDetailList from "@/pages/Futuers/FutuersDetailList";
import {plus} from "@/utils/mathFunc";


const handleAdd = async (fields: OrderTrade) => {
  const hide = message.loading('正在添加');
  try {
    const msg = await orderTrade({...fields});
    hide();
    return queryUseUpdate(msg)
  } catch (error) {
    return false;
  }
};

const FutuersList: React.FC = () => {
    /** 新建窗口的弹窗 */
    /*
  actualAmount: 23.149
  commission: 0.00008464
  contractAmount: 0
  contractCount: 0
  fixedAmount: 100
  group: "202104291655360979"
  leverage: 2
  status: "INTRADE"
  stockAmount: 65.97188773
  stockCount: 47.19
  symbol: "XRPUSDT"
    * */
    const columns: any[] = [
      // {
      //   title: "订单ID",
      //   dataIndex: 'orderId',
      //   search: false,
      //   key: 'orderId',
      //   fixed: "left",
      //   width: 100,
      //   // filters: true,
      //   // onFilter: true,
      //   tip: '订单ID是唯一的 key',
      // },
      {
        title: "交易对",
        search: false,
        dataIndex: 'symbol',
        key: 'symbol',
        fixed: "left",
        width: 100,
      },
      // {
      //   title: "交易组号",
      //   search: false,
      //   dataIndex: 'group',
      //   key: 'group',
      //   fixed: "left",
      //   width: 100,
      // },
      {
        title: "订单类型",
        search: false,
        width: 100,
        dataIndex: 'orderMethod',
        key: 'orderMethod',
      },


      {
        title: "总资产",
        search: false,
        width: 100,
        key: 'assets',
        dataIndex: 'assets',
      },
      {
        title: "套利利润",
        search: false,
        width: 100,
        key: 'arbitrageProfit',
        dataIndex: 'arbitrageProfit',
      },
      {
        title: "套利利润率",
        search: false,
        width: 110,
        key: 'arbitrageProfitRate',
        dataIndex: 'arbitrageProfitRate',
        renderText: (val: number) => formatNumPercent(val, 4)
      },
      {
        title: "总收益",
        search: false,
        width: 110,
        key: 'allProfit',
        dataIndex: 'allProfit',
      },
      {
        title: "浮动盈亏",
        search: false,
        width: 90,
        key: 'floatProfit',
        dataIndex: 'floatProfit',
      },
      {
        title: "年化收益率",
        search: false,
        width: 110,
        key: 'xirr',
        dataIndex: 'xirr',
        renderText: (val: number) => formatNumPercent(val, 4)
      },
      // {
      //   title: "交易时间",
      //   search: false,
      //   width: 120,
      //   dataIndex: 'createTime',
      //   key: 'createTime',
      //   renderText: (val: string) => formatDate(val, false)
      // },
      {
        title: "最后时间",
        search: false,
        width: 120,
        dataIndex: 'endTime',
        key: 'endTime',
        renderText: (val: string) => formatDate(val, false)
      },
      {
        title: "开始时间",
        search: false,
        width: 120,
        dataIndex: 'startTime',
        key: 'startTime',
        renderText: (val: string) => formatDate(val, false)
      },

//现货
      {
        title: "当前现货价格",
        search: false,
        width: 110,
        dataIndex: 'lastStockPrice',
        key: 'lastStockPrice',
      },
      {
        title: "现货交易数量",
        search: false,
        width: 110,
        dataIndex: 'stockCount',
        key: 'stockCount',
      },
      {
        title: "现货金额",
        search: false,
        width: 100,
        dataIndex: 'stockAmount',
        key: 'stockAmount',
      },
      {
        title: "现货浮动盈亏",
        search: false,
        width: 110,
        dataIndex: 'stockProfit',
        key: 'stockProfit',
      },
      {
        title: "现货交易手续费",
        search: false,
        width: 110,
        key: 'commission',
        dataIndex: 'commission',
      },

//合约
      {
        title: "当前合约价格",
        search: false,
        width: 110,
        dataIndex: 'lastContractPrice',
        key: 'lastContractPrice',
      },
      {
        title: "强平价格",
        search: false,
        width: 100,
        dataIndex: 'liquidationPrice',
        key: 'liquidationPrice',
      },
      {
        title: "合约数量",
        search: false,
        width: 100,
        dataIndex: 'contractCount',
        key: 'contractCount',
      },
      {
        title: "合约金额",
        search: false,
        width: 100,
        dataIndex: 'contractAmount',
        key: 'contractAmount',
      },
      {
        title: "合约浮动盈亏",
        search: false,
        width: 110,
        dataIndex: 'contractProfit',
        key: 'contractProfit',
      },
      {
        title: "合约手续费",
        search: false,
        width: 110,
        dataIndex: 'contractCommission',
        key: 'contractCommission',
      },
      {
        title: "合约杠杆",
        search: false,
        width: 100,
        dataIndex: 'leverage',
        key: 'leverage',
      },
      {
        title: "下一次资金费率",
        search: false,
        width: 100,
        dataIndex: 'lastFundingRate',
        key: 'lastFundingRate',
        renderText: (val: number) => formatNumPercent(val, 4)
      },
//操作
      {
        title: "操作",
        search: false,
        width: 280,
        render: (_: any, record: any) => {
          if (record.orderMethod === "close") {
            return <div>
              <a href="javascript:void(0);" onClick={() => {
                handleTradeModal({
                  symbol: record.symbol,
                  group: record.group,
                })
                handleDetailModalVisible(true);
              }}>
                详情
              </a>{' '}
            </div>
          }
          return <div>
            <a href="javascript:void(0);" onClick={() => {
              handleTradeModal({
                symbol: record.symbol,
                group: record.group,
              })
              handleDetailModalVisible(true);
            }}>
              详情
            </a>{' '}
            <Divider type="vertical"/>
            <a href="javascript:void(0);" style={{color: "LightSeaGreen"}} onClick={() => {
              handleTradeModal({
                leverage: record.leverage,
                quoteOrderQty: null,
                orderMethod: "add",
                symbol: record.symbol,
                type: 'MARKET',
              })
              handleModalVisible(true);
            }}>
              加仓
            </a>{' '}
            <Divider type="vertical"/>
            <a href="javascript:void(0);" style={{color: "Darkorange"}} onClick={() => {
              handleTradeModal({
                leverage: record.leverage,
                quoteOrderQty: null,
                orderMethod: "subtract",
                symbol: record.symbol,
                type: 'MARKET',
              })
              handleModalVisible(true)
            }}>
              减仓
            </a>
            <Divider type="vertical"/>
            <Popconfirm title="是否平仓？" onConfirm={() => {
              orderTradeAll({
                orderMethod: "close",
                symbol: record.symbol,
              }).then()
            }}>
              <a href="javascript:void(0);" style={{color: "OrangeRed"}}>
                平仓
              </a>
            </Popconfirm>
          </div>
        }
      },
    ];
    columnsSorter("FutuersList期现套利记录列表", columns);
    const [col, setCol] = useState<any>(columnToColumnsState(columns));

    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [createDetailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
    const [createTradeModal, handleTradeModal] = useState<OrderTrade>({
      leverage: null,
      quoteOrderQty: null,
      orderMethod: null,
      symbol: null,
      type: null,
    });

    const actionRef = useRef<ActionType>();
    const orderTradeAll = async (value: any) => {
      const success = await handleAdd(value as OrderTrade);
      if (success) {
        handleModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
    }
    const columnsWidth = (columns: any[]) => {
      let reCol: number = 0;
      columns.map(a => {
        reCol += (a.width || 100)
      });
      return reCol
    }
    return (
      <PageContainer>
        {/**
         *@table
         */}
        <ProTable<any>
          headerTitle={"期现套利记录列表"}
          // style={{margin:'20px'}}
          bordered
          actionRef={actionRef}
          cardBordered={true}
          search={false}
          columnsStateMap={col}
          onColumnsStateChange={(e) => {
            if (!empty(e)) {
              localStorage.setItem("FutuersList期现套利记录列表", JSON.stringify(e));
              setCol(e);
            }
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleTradeModal({
                  leverage: null,
                  quoteOrderQty: null,
                  orderMethod: "start",
                  symbol: null,
                  type: 'MARKET',
                });
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/>{"开仓"}
            </Button>,
          ]}

          scroll={{x: columnsWidth(columns), y: 666}}
          request={async (params = {}, sort, filter) => {
            let payload: queryType = {
              page: params.current,
              pageSize: params.pageSize,
            }
            // if (params.orderId) {
            //   payload = {...payload}
            // }
            const msg = await queryFutuersList(
              payload
            );
            let data = queryUse(msg)
            if (data) {
              data.list.map((a: any) => {
                // a.floatProfit = bignumber(a.stockProfit||0)+bignumber(a.contractProfit||0;
                a.floatProfit = plus((a.stockProfit || 0), (a.contractProfit || 0));
              })
              console.log(data.list)
              return {
                data: data.list,
                success: true,
                total: data.total,
              };
            } else {
              return {
                data: [],
                success: false,
              };
            }
          }}
          columns={columns}
          pagination={{defaultPageSize: 50}}
          {...{cardProps: {bodyStyle: {paddingBottom: "20px"}}}}
        />

        {/**
         *@modal
         */}
        <Modal
          destroyOnClose
          title={"交易组号 " + createTradeModal.symbol + " 详情"}
          width="80%"
          centered
          footer={false}
          onOk={() => handleDetailModalVisible(false)}
          onCancel={() => handleDetailModalVisible(false)}
          visible={createDetailModalVisible}
        >
          <FutuersDetailList symbol={createTradeModal.symbol} group={createTradeModal.group}/>
        </Modal>

        <ModalForm
          title={'期货现货套利下单'}
          width={400}
          visible={createModalVisible}
          onVisibleChange={handleModalVisible}
          onFinish={async value => {
            await orderTradeAll(value);
          }}

          {...{modalProps: {destroyOnClose: true}}}
        >
          <ProFormSelect
            width={330}
            rules={[{required: true},]}
            initialValue={createTradeModal.orderMethod}
            request={async () => [
              {label: '开仓', value: 'start'},
              {label: '加仓', value: 'add'},
              {label: '减仓', value: 'subtract'},
              {label: '平仓', value: 'close'},
            ]}
            disabled={true}
            name="orderMethod"
            label="交易方向"
          />
          <ProFormSelect
            width={330}
            rules={[{required: true,},]}
            initialValue={createTradeModal.symbol}
            request={async () => {
              const msg = await querySymbols();
              debugger
              let data = queryUse(msg)
              let reList = [];
              for (let key in data) {
                reList.push({
                  label: data[key],
                  value:data[key],
                })
              }
              return reList;
            }}
            name="symbol"
            label="交易对"
          />{/*start,add,subtract,close*/}

          <ProFormSelect
            rules={[{required: true,},]}
            width={330}
            request={async () => [
              {label: 'MARKET', value: 'MARKET'},
            ]}
            name="type"
            label="类型"
            initialValue={createTradeModal.type}
          />
          <ProFormDigit name={"quoteOrderQty"} label="购买金额" width={330} rules={[{required: true,},]}
                        initialValue={createTradeModal.quoteOrderQty}/>
          <ProFormDigit name={"leverage"} label="杠杆" width={330} rules={[{required: true,},]}
                        initialValue={createTradeModal.leverage}/>
        </ModalForm>
      </PageContainer>
    );
  }
;

export default FutuersList;
